import { readdirSync, writeFileSync } from 'fs';
import { basename, join } from 'path';
import { commands, Uri, window, workspace } from 'vscode';
import { config, MessageFormat } from 'vscode-nls';
import generate from '../../util/generate';
import replace from '../../util/replace';

const localize = config({
	messageFormat: MessageFormat.file
})(__filename);

export default function add() {
	return commands.registerCommand('feidao.web.component.add.nodeaction', async (uri: Uri) => {
		const path = uri.fsPath;
		// 如果当前目录不在某个页面中，则不允许操作
		const r = path.match(/[/\\](src-web[/\\]\w[\w\d-]*[/\\]\w[\w\d-]*)[/\\]?/);
		if (r === null) {
			window.showErrorMessage(localize(0));
			return;
		} else {
			const [, dir] = r;
			const folder = join(workspace.getWorkspaceFolder(uri).uri.fsPath, dir);
			create_a(folder);
			await update_n(folder);
			await workspace.saveAll();
		}
	});
}

async function update_n(path: string) {
	const file_name = join(path, 'n.ts');
	const editor = await window.showTextDocument(Uri.file(file_name));
	// const eol = workspace.getConfiguration('files').get<string>('eol');
	const eol = '\n';
	const files = readdirSync(path);
	const as = files.filter((f) => {
		return /^na\d{3}\.ts$/.test(f);
	}).map((f) => {
		return basename(f, '.ts');
	});

	const ims = as.map((a) => {
		return `import ${a} from './${a}';`;
	}).join(eol);

	const imps = `${ims}`;

	await replace(editor, 'IMPACTIONS', imps);

	const actions = `	const actions = { ${as.join(', ')} };`;
	await replace(editor, 'ACTIONS', actions);
}

function create_a(p_path: string) {
	const path = generate(p_path, 'na', '\\.ts', 3);
	const a = basename(path);
	const tpl = `import { IFeidaoAiNodejsComponent } from '@feidao/web/interfaces';

export default async function ${a}(fd: IFeidaoAiNodejsComponent, ...args: any[]) {
	// todo
}
`;
	writeFileSync(path + '.ts', tpl);
}
